﻿using System;
using System.IO;
using System.ServiceModel;
using System.Windows.Forms;
using ServiceLibrary;

namespace Console
{
    public partial class ControlPannel : Form
    {
        private ServiceHost _myHost;
        private ServiceRepository _myService;

        public ControlPannel()
        {
            InitializeComponent();
        }

        #region 开启、关闭服务

        private void StartService()
        {
            try
            {
                using (var db = new IntranetMessagerDBEntities())
                {
                    if (!db.DatabaseExists())
                    {
                        LogOutput("致命错误：数据库未建立或者数据库无权限访问");
                        StartBtn.Enabled = false;
                        return;
                    }
                }

                _myService = new ServiceRepository(LogOutput);
                _myHost = new ServiceHost(_myService);

                _myHost.Opening += MyHostOpening;
                _myHost.Opened += MyHostOpened;
                _myHost.Closing += MyHostClosing;

                _myHost.Open();
            }
            catch (Exception ex)
            {
                LogOutput(ex.Message);
                return;
            }
        }

        private void CloseService()
        {
            if (_myHost == null)
            {
                return;
            }
            if (_myHost.State == CommunicationState.Closed) return;
            _myHost.Close();
        }

        private void MyHostClosing(object sender, EventArgs e)
        {
            LogOutput(string.Format("{0} - Shutdown server...", DateTime.Now));
        }

        private void MyHostOpened(object sender, EventArgs e)
        {
            LogOutput(string.Format("{0} - Start Success!", DateTime.Now));
        }

        private void MyHostOpening(object sender, EventArgs e)
        {
            LogOutput(string.Format("{0} - Server is Starting...", DateTime.Now));
        }

        #endregion

        #region 输出日志

        private void LogOutput(string log)
        {
            if (LogBox.InvokeRequired)
            {
                WriteLogCallback callback = LogOutput;
                var args = new object[] {log};
                Invoke(callback, args);
            }
            else
            {
                LogBox.AppendText(log + Environment.NewLine);
            }
        }

        #endregion

        #region 保存日志

        private void SaveLogToFile()
        {
            saveLogToFileDialog.FileName = string.Format("服务器日志文件_{0}.txt", DateTime.Now.ToLongDateString());
            if (saveLogToFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            try
            {
                File.WriteAllText(saveLogToFileDialog.FileName, LogBox.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, @"Error", MessageBoxButtons.OK);
            }
        }

        #endregion

        private void ControlModifier(IAsyncResult ar)
        {
            if (StartBtn.InvokeRequired)
            {
                ModifyControl modify = ControlModifier;
                var args = new object[] {ar};
                Invoke(modify, args);
            }
            else
            {
                Text = @"服务器控制台 - 已启动";
                StartBtn.Text = @"Started";
                CloseBtn.Text = @"Exit";
                CloseBtn.Enabled = true;
                CloseBtn.Focus();
            }
        }

        private void StartBtnClick(object sender, EventArgs e)
        {
            Text = @"服务器控制台 - 正在启动";
            StartBtn.Text = @"Starting...";
            StartBtn.Enabled = false;
            CloseBtn.Text = @"Wait...";
            CloseBtn.Enabled = false;
            StartServiceDelegate startService = StartService;
            startService.BeginInvoke(ControlModifier, null);
        }

        private void CloseBtnClick(object sender, EventArgs e)
        {
            CloseService();

            DialogResult result = MessageBox.Show(this, @"是否保存日志文件？", @"保存日志", MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

            if (result == DialogResult.Yes)
            {
                SaveLogToFile();
                Application.Exit();
            }
            else
            {
                Application.Exit();
            }
        }

        #region Nested type: ModifyControl

        private delegate void ModifyControl(IAsyncResult ar);

        #endregion

        #region Nested type: StartServiceDelegate

        private delegate void StartServiceDelegate();

        #endregion

        #region Nested type: WriteLogCallback

        private delegate void WriteLogCallback(string log);

        #endregion
    }
}